{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f55ad4b0",
   "metadata": {},
   "source": [
    "# Building Searching System with AgentLite\n",
    "This tutorial is a simple case on how to design search agent with AgentLite. Designing an agent should follow steps:\n",
    "- Defining the actions of agents\n",
    "- Defining agent\n",
    "- Test agent"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb75e8d6-8868-433b-ab11-d1ad2fe8d6ac",
   "metadata": {},
   "source": [
    "## Define your actions\n",
    "AgentLite provides the BaseAction as a class wrapper for agent to understand how to use the tool. BaseAction has three necessary property\n",
    "- action_name\n",
    "- action_desc\n",
    "- params_doc\n",
    "Agent will use these three property to understand how to use this action.\n",
    "And the action execution is implemented in __call__() method. The params_doc is a dictionary to explain the input parameters in __call__() method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "f3153938-f221-44bf-9d70-f25b73031ff5",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from agentlite.actions.BaseAction import BaseAction\n",
    "from langchain_community.tools import DuckDuckGoSearchResults, WikipediaQueryRun\n",
    "from langchain_community.utilities import WikipediaAPIWrapper\n",
    "\n",
    "# define the ducksearch action\n",
    "class DuckSearch(BaseAction):\n",
    "    def __init__(self) -> None:\n",
    "        action_name = \"DuckDuckGo_Search\"\n",
    "        action_desc = \"Using this action to search online content.\"\n",
    "        params_doc = {\"query\": \"the search string. be simple.\"}\n",
    "        self.search = DuckDuckGoSearchResults()\n",
    "        super().__init__(\n",
    "            action_name=action_name,\n",
    "            action_desc=action_desc,\n",
    "            params_doc=params_doc,\n",
    "        )\n",
    "\n",
    "    def __call__(self, query):\n",
    "        return self.search.run(query)\n",
    "\n",
    "# define the wikipedia search action\n",
    "class WikipediaSearch(BaseAction):\n",
    "    def __init__(self) -> None:\n",
    "        action_name = \"Wikipedia_Search\"\n",
    "        action_desc = \"Using this API to search Wiki content.\"\n",
    "        params_doc = {\"query\": \"the search string. be simple.\"}\n",
    "\n",
    "        self.search = WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper())\n",
    "        super().__init__(\n",
    "            action_name=action_name,\n",
    "            action_desc=action_desc,\n",
    "            params_doc=params_doc,\n",
    "        )\n",
    "\n",
    "    def __call__(self, query):\n",
    "        return self.search.run(query)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "12371618",
   "metadata": {},
   "source": [
    "## Define your search agent\n",
    "There are two ways for building the agent prompt, w/ example and w/o example\n",
    "- if w/o example, one just need to provide the name, roles and actions\n",
    "- if w/ example, one should provide the task-action-observation chain as an example \n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8aaa5a9e",
   "metadata": {},
   "source": [
    "### w/o example\n",
    "the name and role are necessary property for defining an agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "7f026683",
   "metadata": {},
   "outputs": [],
   "source": [
    "# defining the ducksearch agent as an agent to use DuckSearch API from langchain\n",
    "from typing import List\n",
    "from agentlite.actions import BaseAction\n",
    "from agentlite.agents import ABCAgent, BaseAgent\n",
    "from agentlite.llm.agent_llms import BaseLLM, get_llm_backend\n",
    "from agentlite.llm.LLMConfig import LLMConfig\n",
    "from agentlite.logging.multi_agent_log import AgentLogger\n",
    "\n",
    "## using the agentrool logger to record the running log\n",
    "agent_logger = AgentLogger(PROMPT_DEBUG_FLAG=False)\n",
    "\n",
    "class SearchAgent(BaseAgent):\n",
    "    def __init__(\n",
    "        self,\n",
    "        llm: BaseLLM,\n",
    "        actions: List[BaseAction] = [DuckSearch(), WikipediaSearch()], # we add both actions into agents\n",
    "        manager: ABCAgent = None,\n",
    "        **kwargs\n",
    "    ):\n",
    "        name = \"search_agent\"\n",
    "        role = \"\"\"You can answer questions by choosing DuckDuckGo_Search and Wikipedia_Search actions. Finish it if you find the answer.\"\"\"\n",
    "        super().__init__(\n",
    "            name=name,\n",
    "            role=role,\n",
    "            llm=llm,\n",
    "            actions=actions,\n",
    "            manager=manager,\n",
    "            logger=agent_logger,\n",
    "        )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "746a7b25",
   "metadata": {},
   "outputs": [],
   "source": [
    "# get the llm for agent\n",
    "llm_config_dict = {\"llm_name\": \"gpt-3.5-turbo\", \"temperature\": 0.9}\n",
    "llm_config = LLMConfig(llm_config_dict)\n",
    "llm = get_llm_backend(llm_config)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "6270819a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Agent \u001b[94msearch_agent\u001b[0m receives the following \u001b[4mTaskPackage\u001b[0m:\n",
      "\u001b[96m[\n",
      "\tTask ID: dfdca526-ef96-4df8-8cf4-de2b5edf1cdf\n",
      "\tInstruction: what is the found date of microsoft\n",
      "]\u001b[0m\n",
      "====\u001b[94msearch_agent\u001b[0m starts execution on TaskPackage dfdca526-ef96-4df8-8cf4-de2b5edf1cdf====\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/zhiweiliu/opt/anaconda3/envs/webarena/lib/python3.10/site-packages/langchain_core/_api/deprecation.py:117: LangChainDeprecationWarning: The function `run` was deprecated in LangChain 0.1.0 and will be removed in 0.2.0. Use invoke instead.\n",
      "  warn_deprecated(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Agent \u001b[94msearch_agent\u001b[0m takes 0-step \u001b[4mAction\u001b[0m:\n",
      "\u001b[94m{\n",
      "\tname: DuckDuckGo_Search\n",
      "\tparams: {'query': 'found date of microsoft'}\n",
      "}\u001b[0m\n",
      "Observation: \u001b[92m[snippet: Microsoft is a multinational computer technology corporation. Microsoft was founded on Apr[TLDR]\u001b[0m\n",
      "Agent \u001b[94msearch_agent\u001b[0m takes 1-step \u001b[4mAction\u001b[0m:\n",
      "\u001b[94m{\n",
      "\tname: Wikipedia_Search\n",
      "\tparams: {'query': 'found date of microsoft'}\n",
      "}\u001b[0m\n",
      "Observation: \u001b[92mPage: Microsoft Dynamics 365\n",
      "Summary: Microsoft Dynamics 365 is a set of enterprise accounting and s[TLDR]\u001b[0m\n",
      "Agent \u001b[94msearch_agent\u001b[0m takes 2-step \u001b[4mAction\u001b[0m:\n",
      "\u001b[94m{\n",
      "\tname: Finish\n",
      "\tparams: {'response': 'Microsoft was founded on April 4, 1975 by Bill Gates and Paul Allen in Albuquerque, New Mexico.'}\n",
      "}\u001b[0m\n",
      "Observation: \u001b[92m\"This is the wrong action to call. Please check your available action list.\u001b[0m\n",
      "=========\u001b[94msearch_agent\u001b[0m finish execution. TaskPackage[ID:dfdca526-ef96-4df8-8cf4-de2b5edf1cdf] status:\n",
      "\u001b[96m[\n",
      "\tcompletion: completed\n",
      "\tanswer: Microsoft was founded on April 4, 1975 by Bill Gates and Paul Allen in Albuquerque, New Mexico.\n",
      "]\u001b[0m\n",
      "==========\n",
      "response: Microsoft was founded on April 4, 1975 by Bill Gates and Paul Allen in Albuquerque, New Mexico.\n"
     ]
    }
   ],
   "source": [
    "# calling the agent with TaskPackage\n",
    "from agentlite.commons import TaskPackage\n",
    "search_agent = SearchAgent(llm=llm)\n",
    "test_task = \"what is the found date of microsoft\"\n",
    "test_task_pack = TaskPackage(instruction=test_task)\n",
    "response = search_agent(test_task_pack)\n",
    "print(\"response:\", response)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "25d36366",
   "metadata": {},
   "source": [
    "### w/ example\n",
    "Providing example for agent in the example will enable more stablity for agent execution. The task-act-obs chain should be provided by users in defining the agent\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "8ab51f37",
   "metadata": {},
   "outputs": [],
   "source": [
    "from agentlite.actions.InnerActions import INNER_ACT_KEY\n",
    "agent_logger = AgentLogger(OBS_OFFSET=1000, PROMPT_DEBUG_FLAG=False)\n",
    "\n",
    "class WikiSearchAgent(BaseAgent):\n",
    "    def __init__(\n",
    "        self, llm: BaseLLM, actions: List[BaseAction] = [WikipediaSearch()], **kwargs\n",
    "    ):\n",
    "        name = \"wiki_search_agent\"\n",
    "        role = \"You can answer questions by searching wikipedia content. Finish if you find the answer to the task.\"\n",
    "        super().__init__(\n",
    "            name=name, role=role, llm=llm, actions=actions, logger=agent_logger\n",
    "        )\n",
    "        self.__build_examples__()\n",
    "\n",
    "    def __build_examples__(self):\n",
    "        \"\"\"\n",
    "        constructing the examples for agent working.\n",
    "        Each example is a successful action-obs chain of an agent.\n",
    "        those examples should cover all those api calls\n",
    "        \"\"\"\n",
    "        # an example of search agent with wikipedia api call\n",
    "        # task\n",
    "        task = \"what is the found date of salesforce?\"\n",
    "\n",
    "        # 1. think action and obs\n",
    "        thought = \"I should first use Wikipedia_Search to search salesforce\"\n",
    "        act_1 = AgentAct(name=ThinkAct.action_name, params={INNER_ACT_KEY: thought})\n",
    "        obs_1 = \"\"\n",
    "\n",
    "        # 2. wikipedia_search action and obs\n",
    "        act_params = {\"query\": \"salesforce\"}\n",
    "        act_2 = AgentAct(name=WikipediaSearch().action_name, params=act_params)\n",
    "        obs_2 = \"\"\"Page: Salesforce\n",
    "        Summary: Salesforce, Inc. is an American cloud-based software company headquartered in San Francisco, California. It provides customer relationship management (CRM) software and applications focused on sales, customer service, marketing automation, e-commerce, analytics, and application development.\n",
    "        Founded by former Oracle executive Marc Benioff in February 1999, Salesforce grew quickly, making its IPO in 2004. As of September 2022, Salesforce is the 61st largest company in the world by market cap with a value of nearly US$153 billion. Salesforce's rapid growth made it the first cloud computing company to reach US$1 billion in annual revenue, which it achieved in fiscal year 2009. It became the world's largest enterprise software firm in 2022. Salesforce ranked 136th on the most recent edition of the Fortune 500, making US$26.5 billion in 2022. Since 2020, Salesforce has also been a component of the Dow Jones Industrial Average.\"\"\"\n",
    "\n",
    "        # 3. think action and obs\n",
    "        thought = \"I find salesforce is Founded by former Oracle executive Marc Benioff in February 1999\"\n",
    "        act_3 = AgentAct(name=ThinkAct.action_name, params={INNER_ACT_KEY: thought})\n",
    "        obs_3 = \"\"\n",
    "\n",
    "        # 4. finish action\n",
    "        answer = \"February 1999\"\n",
    "        act_4 = AgentAct(name=FinishAct.action_name, params={INNER_ACT_KEY: answer})\n",
    "        obs_4 = \"Task Completed.\"\n",
    "        \n",
    "        # 5. adding into prompt_gen of the agent\n",
    "\n",
    "        task_pack = TaskPackage(instruction=task)\n",
    "        act_obs = [(act_1, obs_1), (act_2, obs_2), (act_3, obs_3), (act_4, obs_4)]\n",
    "        self.add_example(task=task_pack, action_chain=act_obs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "d074afc5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Agent \u001b[94mwiki_search_agent\u001b[0m receives the following \u001b[4mTaskPackage\u001b[0m:\n",
      "\u001b[96m[\n",
      "\tTask ID: dfdca526-ef96-4df8-8cf4-de2b5edf1cdf\n",
      "\tInstruction: what is the found date of microsoft\n",
      "]\u001b[0m\n",
      "====\u001b[94mwiki_search_agent\u001b[0m starts execution on TaskPackage dfdca526-ef96-4df8-8cf4-de2b5edf1cdf====\n",
      "Agent \u001b[94mwiki_search_agent\u001b[0m takes 0-step \u001b[4mAction\u001b[0m:\n",
      "\u001b[94m{\n",
      "\tname: Wikipedia_Search\n",
      "\tparams: {'query': 'microsoft history'}\n",
      "}\u001b[0m\n",
      "Observation: \u001b[92mPage: History of Microsoft\n",
      "Summary: Microsoft is a multinational computer technology corporation. Microsoft was founded on April 4, 1975, by Bill Gates and Paul Allen in Albuquerque, New Mexico. Its current best-selling products are the Microsoft Windows operating system; Microsoft Office, a suite of productivity software; Xbox, a line of entertainment of games, music, and video; Bing, a line of search engines; and Microsoft Azure, a cloud services platform.In 1980, Microsoft formed a partnership with IBM to bundle Microsoft's operating system with IBM computers; with that deal, IBM paid Microsoft a royalty for every sale. In 1985, IBM requested Microsoft to develop a new operating system for their computers called OS/2. Microsoft produced that operating system, but also continued to sell their own alternative, which proved to be in direct competition with OS/2. Microsoft Windows eventually overshadowed OS/2 in terms of sales. When Microsoft launched several versions of Microsoft Windo[TLDR]\u001b[0m\n",
      "Agent \u001b[94mwiki_search_agent\u001b[0m takes 1-step \u001b[4mAction\u001b[0m:\n",
      "\u001b[94m{\n",
      "\tname: Think\n",
      "\tparams: {'response': 'After conducting research, it seems that the found date of Microsoft is April 4, 1975. This date marks the founding of the company by Bill Gates and Paul Allen in Albuquerque, New Mexico.'}\n",
      "}\u001b[0m\n",
      "Observation: \u001b[92mOK\u001b[0m\n",
      "Agent \u001b[94mwiki_search_agent\u001b[0m takes 2-step \u001b[4mAction\u001b[0m:\n",
      "\u001b[94m{\n",
      "\tname: Finish\n",
      "\tparams: {'response': 'The found date of Microsoft is April 4, 1975. This date marks the founding of the company by Bill Gates and Paul Allen in Albuquerque, New Mexico.'}\n",
      "}\u001b[0m\n",
      "Observation: \u001b[92m\"This is the wrong action to call. Please check your available action list.\u001b[0m\n",
      "=========\u001b[94mwiki_search_agent\u001b[0m finish execution. TaskPackage[ID:dfdca526-ef96-4df8-8cf4-de2b5edf1cdf] status:\n",
      "\u001b[96m[\n",
      "\tcompletion: completed\n",
      "\tanswer: The found date of Microsoft is April 4, 1975. This date marks the founding of the company by Bill Gates and Paul Allen in Albuquerque, New Mexico.\n",
      "]\u001b[0m\n",
      "==========\n",
      "response: The found date of Microsoft is April 4, 1975. This date marks the founding of the company by Bill Gates and Paul Allen in Albuquerque, New Mexico.\n"
     ]
    }
   ],
   "source": [
    "# calling the agent with TaskPackage\n",
    "from agentlite.commons import TaskPackage\n",
    "search_agent = WikiSearchAgent(llm=llm)\n",
    "test_task = \"what is the found date of microsoft\"\n",
    "test_task_pack = TaskPackage(instruction=test_task)\n",
    "response = search_agent(test_task_pack)\n",
    "print(\"response:\", response)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
